<?php

class RankingController extends BaseController {
        
    public function indexAction($requestData) {
		$this->data['pageTitle'] = 'Current Ranking - Peak 100';
		
		$this->data['events'] = p1_event::getAll();
		
		$eventsRaw = p1_event::getAll(array(), array(), 150);
		$events = array();
		foreach($eventsRaw as $e) {
			$events[$e->id] = $e;
		}
		$votes = p1_vote::getAll(array("calculated"=>"0"), array("id", "DESC"));
		
		$last_update = p1_calculation::getAll(array(), array("id", "DESC"), 1);
		if(empty($last_update)) {
			if(!empty($votes)) {
				$this->data['last_update'] = $votes[0]->created;
			} else {
				$this->data['last_update'] = strtotime("2009-10-28 04:48:00");
			}
		} else {
			$this->data['last_update'] = $last_update[0]->created; 
		}
		
		$this->data['next_update'] = strtotime($this->data['last_update']) + 2*365*24*60*60;
		
		
		foreach($votes as $v) {
			$events[$v->event]->votes++;
			$events[$v->event]->score += ($v->distance + $v->time_to_complete + $v->terrain + $v->climate + $v->factor + $v->support);
		}
		
		foreach($events as $e) {
			if(isset($e->score)) {
				$avg = $e->score/$e->votes;
				
				$index = $avg . "." . $e->votes;
				if(isset($ranking[$index])) {
					$index .= ".". $e->rank;
				}
				
				$ranking[$index] = $e;				
				$ranking[$index]->avg = $avg;
			} else {
				$index = "0.0".$e->rank;
				$ranking[$index] = $e;
				$ranking[$index]->avg = "0";
			}
		}
		
		krsort($ranking);
		$this->data['ranking'] = $ranking;
    
		if(pk_user::isLoggedIn()) {
			$this->data['user'] = pk_user::get($_SESSION['pk_user']);
			$this->data['profile'] = pk_profile::get($this->data['user']->id, "user");
		}
		if(p1_admin::isLoggedIn()) {
			$this->data['admin'] = p1_admin::get($_SESSION['p1_admin']);
		}
    }
    
    public function resultAction($request) { 
    	$this->data['events'] = p1_event::getAll();
    	$this->data['pageTitle'] = "Ranking Result - Peak 100";
    	
    	$calcs = p1_calculation::getAll(array(), array("id", "DESC"));
    	if(empty($calcs)) {
    		$this->data['no_result'] = true;
    		return;
    	} else {
    		if(count($calcs) == 1) {
    			$this->data['calc_from'] = strtotime("2009-10-28 04:48:00");
    			$this->data['calc_to'] = $calcs[0]->created;
    		} else {
    			$this->data['calc_to'] = $calcs[0]->created;
    			$this->data['calc_from'] = $calcs[1]->created;
    		}
    	}
    	
    	// get latest scores
    	$scoresRaw = p1_score::getAll(array("calculated"=>$calcs[0]->id));
    	$scores = array();
    	foreach($scoresRaw as $s) {
    		$scores[$s->event] = $s;
    	}
    	
    	$events = array();
    	$count = 0;
    	foreach($this->data['events'] as $e) {
    		$events[$count] = $e;
    		$events[$count]->score = $scores[$e->id];
    		$count++;
    	}
    	
    	$this->data['results'] = $events;
    	
    }

}

?>